package com.example.demo.Control;

import com.example.demo.Component.WebSocketComponent;
import com.example.demo.Entity.*;
import com.example.demo.Service.MessageService;
import com.example.demo.Service.MessageSessionService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

@Component
public class WebSocket extends TextWebSocketHandler {
    @Autowired
    public WebSocketComponent webSocketComponent;
   @Autowired
    public ObjectMapper objectMapper;
   @Autowired
   public MessageSessionService messageSessionService;
   @Autowired
    public MessageService messageService;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("[websocket]连接成功");
       Userinfo userinfo=(Userinfo) session.getAttributes().get("userinfo");
       if(userinfo==null){
           return;
       }
       webSocketComponent.online(userinfo.getUserid(), session);
        System.out.println(userinfo.getUserid()+"上线");
    }
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("[websocket]收到消息"+message.toString());
        Userinfo userinfo=(Userinfo) session.getAttributes().get("userinfo");
        if(userinfo==null){
            System.out.println("[websocket]当前用户未登录");
            return;
        }
        //进行数据转化
        System.out.println(message.getPayload().toString()+"message");
        MessageRequest req =objectMapper.readValue(message.getPayload(),MessageRequest.class);
        System.out.println(req.toString()+"req");
        System.out.println(req.getType()+"type");
        if(req.getType().equals("message")){
            //进行消息转发
            tranceferMessage(userinfo,req);
        }else{
            System.out.println("[websocket]--req.type有误");
            return;
        }
    }
    public void tranceferMessage(Userinfo fromUser,MessageRequest req) throws IOException {
        //构造一个响应对象
        MessageResponse messageResponse=new MessageResponse();
        messageResponse.setFromId(fromUser.getUserid());
        messageResponse.setFromName(fromUser.getUsername());
        messageResponse.setSessionId(req.getSessionId());
        messageResponse.setContent(req.getContent());
        String respJson=objectMapper.writeValueAsString(messageResponse);
        //查找sessionId中的用户
        List<Friend> list=messageSessionService.getUserid(req.getSessionId(), fromUser.getUserid());
        //添加自己用户
        Friend myself=new Friend();
        myself.setFriendId(fromUser.getUserid());
        myself.setFriendName(fromUser.getUsername());
        list.add(myself);
        for (Friend item:list) {
            //根据用户Id 等到WebSession
          WebSocketSession session= (WebSocketSession) webSocketComponent.getSession(item.getFriendId());
          if(session==null){
              continue;
          }
            //发送消息
           session.sendMessage(new TextMessage(respJson));
          //将数据存储到数据库中
            MessageEntity messageEntity=new MessageEntity();
            messageEntity.setSessionId(req.getSessionId());
            messageEntity.setFromId(fromUser.getUserid());
            messageEntity.setContent(req.getContent());
            messageService.addMessage(messageEntity);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        Userinfo userinfo=(Userinfo) session.getAttributes().get("userinfo");
        if (userinfo==null){
            return;
        }
        webSocketComponent.offline(userinfo.getUserid(), session);
        System.out.println("[websocket]连接异常");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Userinfo userinfo=(Userinfo) session.getAttributes().get("userinfo");
        if (userinfo==null){
            return;
        }
        webSocketComponent.offline(userinfo.getUserid(), session);
        System.out.println("[websocket]连接关闭");
    }


}
